package com.xique.park.controller.client.web.service.biz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xique.common.core.utils.AliossUtil;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.utils.command.CommandResultUtil;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.bean.domain.ParkOn;
import com.xique.park.constant.CommandConstant;
import com.xique.park.constant.ParkApiName;
import com.xique.park.controller.client.web.api.ClientServiceName;
import com.xique.park.controller.client.web.api.IClientCommandApi;
import com.xique.park.controller.client.web.bean.domain.ClientParkApiConfig;
import com.xique.park.controller.client.web.bean.request.ClientOprGateRequest;
import com.xique.park.controller.client.web.service.biz.service.IClientCommandService;
import com.xique.park.controller.client.web.service.service.IClientParkApiConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: caogq
 * @Date: 2021/7/31 10:28
 * @Description:
 */
@Service
public class ClientCommandServiceImpl implements IClientCommandService {

    @Autowired
    IClientCommandApi clientCommandApi;

    @Autowired
    IClientParkApiConfigService clientParkApiConfigService;

    @Autowired
    private AliossUtil aliossUtil;

    /**
     * 开闸测试
     */
    @Override
    public AjaxResult openGate(ClientOprGateRequest request) {
        JSONObject obj = getBaseObj(SecurityUtils.getParkId(), request.getSn(), ClientServiceName.COMMANDSETGATE);
        //增加备注信息、操作人等详细信息
        JSONObject dtObj = new JSONObject();
        dtObj.put("remark", request.getRemark());
        dtObj.put("parkId", SecurityUtils.getParkId());
        dtObj.put("clientId", SecurityUtils.getClientId());
        dtObj.put("userId", SecurityUtils.getUserId());
        obj.put("data", dtObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = clientCommandApi.openOrGate(params);
        return CommandResultUtil.handleCommandResult(commandResult,"");
    }

    /**
     * 关闸
     */
    @Override
    public AjaxResult closeGate(ClientOprGateRequest request) {
        JSONObject obj = getBaseObj(SecurityUtils.getParkId(), request.getSn(), ClientServiceName.COMMANDCLOSEGATE);
        //增加备注信息、操作人等详细信息
        JSONObject dtObj = new JSONObject();
        dtObj.put("remark", request.getRemark());
        dtObj.put("parkId", SecurityUtils.getParkId());
        dtObj.put("clientId", SecurityUtils.getClientId());
        dtObj.put("userId", SecurityUtils.getUserId());
        obj.put("data", dtObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = clientCommandApi.openOrGate(params);
        return CommandResultUtil.handleCommandResult(commandResult,"");
    }

    @Override
    public AjaxResult openGate(String sn) {
        if (StringUtils.isEmpty(sn)) {
            return AjaxResult.error("设备序列号不能为空");
        }
        JSONObject obj = getBaseObj(SecurityUtils.getParkId(), sn, ClientServiceName.COMMANDSETGATE);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = clientCommandApi.openOrGate(params);
        return CommandResultUtil.handleCommandResult(commandResult,"");
    }

    @Override
    public AjaxResult closeGate(String sn) {
        if (StringUtils.isEmpty(sn)) {
            return AjaxResult.error("设备序列号不能为空");
        }
        JSONObject obj = getBaseObj(SecurityUtils.getParkId(), sn, ClientServiceName.COMMANDCLOSEGATE);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = clientCommandApi.openOrGate(params);
        return CommandResultUtil.handleCommandResult(commandResult,"");
    }

    @Override
    public AjaxResult trigPic(String sn) {
        JSONObject obj = getBaseObj(SecurityUtils.getParkId(), sn, ClientServiceName.COMMANDTRIGPIC);
        obj.put("version", "3.0");

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult result = clientCommandApi.trigPic(params);
        String data1 = (String) result.get("data");
        if (StringUtils.isEmpty(data1)) {
            return AjaxResult.error("抓拍图片失败");
        }
        JSONObject dataObj = JSONObject.parseObject(data1);
        if (null == dataObj) {
            return AjaxResult.error("抓拍图片失败");
        }
        if (null == (dataObj.getJSONObject("dt"))) {
            return AjaxResult.error("抓拍图片失败");
        }
        String picPath = dataObj.getJSONObject("dt").getString("pic_path");
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotEmpty(picPath)) {
            String picUrl = aliossUtil.getJzyGetObjectUrl(picPath).toString();
            map.put("picUrl", picUrl);
            map.put("objectName", picPath);
            return AjaxResult.success("图片抓拍成功", map);
        } else {
            return AjaxResult.error("抓拍图片失败");
        }
    }

    @Override
    public AjaxResult markCarInOrOut(Long parkId, String sn, String isGate, ParkOn parkOn) {
        JSONObject obj = getBaseObj(parkId, sn, ParkApiName.COMMAND_MARK_CAR_IN_OR_OUT, ParkApiName.VER_2_0);
        JSONObject dtObj = new JSONObject();
        dtObj.put("plate", parkOn.getPlate());
        //默认颜色传1，后面有需求再从前端获取
//        dtObj.put("color", 1);
        dtObj.put("platetype", ObjectUtil.isEmpty(parkOn.getPlateType()) ? 1 : parkOn.getPlateType());
        dtObj.put("date", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, parkOn.getInTime()));
        //新增，是否开闸处理
        if (StringUtils.isEmpty(isGate)) {
            dtObj.put("is_no_open_gate", 0);
        } else {
            if ("Y".equals(isGate)) {
                dtObj.put("is_no_open_gate", 0);
            } else if ("N".equals(isGate)) {
                dtObj.put("is_no_open_gate", 1);
            }
        }
        obj.put(CommandConstant.DATA, dtObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = clientCommandApi.markCarInOrOut(params);
        return CommandResultUtil.handleCommandResult(commandResult,"");
    }

    @Override
    public AjaxResult updateSpaces(Long parkId, Long garageId) {
        JSONObject obj = getBaseObj(parkId, "", ParkApiName.COMMAND_UPDATE_SPACES);
        JSONObject dtObj = new JSONObject();
        dtObj.put("parkId", parkId);
        dtObj.put("garageId", garageId);
        obj.put(CommandConstant.DATA, dtObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = clientCommandApi.updateSpaces(params);
        return CommandResultUtil.handleCommandResult(commandResult,"");
    }

    /**
     * 请求信息基础obj封装
     *
     * @param sn 设备序列号
     */
    private JSONObject getBaseObj(Long parkId, String sn, String serviceName) {
        JSONObject obj = new JSONObject();
        ClientParkApiConfig parkApiConfig = getParkApiConfig(parkId);
        obj.put("mqtt_key", parkApiConfig.getMqttKey());
        obj.put("charset", "UTF-8");
        obj.put("service", serviceName);
        obj.put("version", "1.0");
        obj.put("sign", "123456789456");
        obj.put("ts", System.currentTimeMillis() / 1000);
        obj.put("device_code", sn);
        return obj;
    }

    private JSONObject getBaseObj(Long parkId, String sn, String serviceName, String version) {
        JSONObject obj = new JSONObject();
        ClientParkApiConfig parkApiConfig = getParkApiConfig(parkId);
        obj.put("mqtt_key", parkApiConfig.getMqttKey());
        obj.put("charset", "UTF-8");
        obj.put("service", serviceName);
        obj.put("version", version);
        obj.put("sign", "123456789456");
        obj.put("ts", System.currentTimeMillis() / 1000);
        obj.put("device_code", sn);
        return obj;
    }

    /**
     * 根据车场id获取车场的服务配置
     */
    public ClientParkApiConfig getParkApiConfig(Long parkId) {
        ClientParkApiConfig parkApiConfig = new ClientParkApiConfig();
        QueryWrapper<ClientParkApiConfig> queryWrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("status", "normal");
        map.put("record_status", "normal");
        map.put("park_id", parkId);
        queryWrapper.allEq(map);
        List<ClientParkApiConfig> list = clientParkApiConfigService.list(queryWrapper);
        //如果为空的话，表示没有配置，填充默认的配置
        if (org.springframework.util.CollectionUtils.isEmpty(list)) {
            parkApiConfig.setMqttKey("mqtt_jzy");
            parkApiConfig.setMqttDomain("121.196.50.46");
            parkApiConfig.setMqttUsrName("");
            parkApiConfig.setMqttUsrPwd("");
            parkApiConfig.setMqttQos(0);
        } else {
            parkApiConfig = list.get(0);
        }
        return parkApiConfig;
    }

}
